<template>
  <a-drawer
    title="标记"
    :closable="false"
    :maskClosable="false"
    :width="500"
    :visible="visible"
    :confirmLoading="confirmLoading"
  >
    <a-spin :spinning="confirmLoading">
      <a-checkbox-group v-model="checkedIds">
        <a-row :gutter="24">
          <a-col :md="24" :sm="24" v-for="item in tagList" :key="item.id">
            <a-checkbox :value="item.id" style="margin-bottom: 20px">
              {{ item.name }}
            </a-checkbox>
          </a-col>
        </a-row>
      </a-checkbox-group>
    </a-spin>
    <div class="drawer-footer">
      <a-button class="left" @click="handleCancel"> 关闭</a-button>
      <a-button class="right" type="primary" @click="handleSubmit"> 提交</a-button>
    </div>
  </a-drawer>
</template>

<script>
  import { homeworkTagList } from '@/api/modular/system/homeworkTagManage'
  import { homeworkTagRelationSave } from '@/api/modular/main/homeworkTagRelationManage'

  export default {
    data() {
      return {
        visible: false,
        confirmLoading: false,
        tagList: [],
        record: {},
        checkedIds: []
      }
    },
    methods: {
      // 初始化方法
      open(record) {
        this.record = record
        if (record.homeworkTagIds) this.checkedIds = record.homeworkTagIds.split(',')
        this.loadHomeworkTagList()
        this.visible = true
      },
      loadHomeworkTagList() {
        homeworkTagList().then((res) => {
          if (res.success) {
            this.tagList = res.data
          }
        })
      },
      /**
       * 提交表单
       */
      handleSubmit() {
        this.confirmLoading = true
        const params = this.checkedIds.map((homeworkTagId) => {
          return {
            homeworkId: this.record.homeworkId,
            homeworkTagId: homeworkTagId
          }
        })
        homeworkTagRelationSave(params)
          .then((res) => {
            if (res.success) {
              this.$message.success('保存成功')
              this.confirmLoading = false
              this.$emit('ok')
              this.handleCancel()
            } else {
              this.$message.error('保存失败') // + res.message
            }
          })
          .finally((res) => {
            this.confirmLoading = false
          })
      },
      handleCancel() {
        this.visible = false
        this.tagList = []
        this.record = {}
        this.checkedIds = []
      }
    }
  }
</script>

<style lang="less" scoped>
</style>
